package JPetStore.web.servlet;

import JPetStore.domain.Account;
import JPetStore.domain.Cart;
import JPetStore.domain.CartItem;
import JPetStore.domain.Item;
import JPetStore.persistence.CartDao;
import JPetStore.persistence.impl.CartDaoImpl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

public class CartJQueryServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try{
            String itemId = req.getParameter("itemId");
            String action = req.getParameter("action");
            int quantity = Integer.parseInt(req.getParameter("quantity"));

            //修改数据库与会话数据
            HttpSession session = req.getSession();
            Cart cart = (Cart) session.getAttribute("cart");

            int j=0;
            for(int i=0;i<cart.getCartItemList().size();i++){
                if(Objects.equals(cart.getCartItemList().get(i).getItem().getItemId(), itemId)) {
                    j=i;
                }
            }
            cart.getCartItemList().get(j).setQuantity(quantity);     //会话cartItem修改
            Account loginAccount = (Account) session.getAttribute("loginAccount");
            CartDao cartDao = new CartDaoImpl();
            cartDao.updateCart(loginAccount,cart.getCartItemList().get(j));

            //remove情况
            if(Objects.equals(action, "remove")){
                cart.getCartItemList().remove(j);
            }
            session.setAttribute("cart",cart);  //上传cart修改

            JSONObject response = new JSONObject();
            response.put("success", true);
            if(Objects.equals(action, "update")) {
                response.put("totalCost", cart.getCartItemList().get(j).getTotal());
            }
            response.put("subTotal", cart.getSubTotal());
            resp.setContentType("application/json");
            resp.getWriter().write(response.toString());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
